package com.zst.dollars.handler.client;

import com.zst.dollars.entity.connection.ClientDisconnectAnnounceMessage;
import com.zst.dollars.entity.msg.ServerMsgBoardcastMessage;
import com.zst.dollars.entity.signin.ClientSignInAnnounceMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 统一处理服务端发送的广播消息的Handler
 */
public class MsgInboundHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(MsgInboundHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        boolean release = true;

        if(msg instanceof ClientDisconnectAnnounceMessage){
            logger.info("用户{}已离开聊天室", ((ClientDisconnectAnnounceMessage) msg).getUsername());
        }else if(msg instanceof ClientSignInAnnounceMessage){
            logger.info("用户{}已进入聊天室", ((ClientSignInAnnounceMessage) msg).getUsername());
        }else if(msg instanceof ServerMsgBoardcastMessage){
            logger.info("{}: {}", ((ServerMsgBoardcastMessage) msg).getUsername(), ((ServerMsgBoardcastMessage) msg).getMessage());
        }else{
            release = false;
        }

        if(release){
            ReferenceCountUtil.refCnt(msg);
        }
    }
}
